package com.fcscs.cservice.dao.hibernate;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fcscs.core.dao.ConnectionManager;
import com.fcscs.core.domain.BaseEntity.DBLoc;
import com.fcscs.cservice.dao.InRoomMenuDao;
import com.fcscs.cservice.domain.InRoomMenu;

@SuppressWarnings("unchecked")
@Repository("inRoomMenuDao")
public class InRoomMenuDaoHibernate extends BaseDaoHibernate<InRoomMenu> implements InRoomMenuDao {

	private static final String DEL_ALL = "delete from in_room_menu where org_id = :orgId and property_id = :propertyId ";

	private static DBLoc DBLoc = new InRoomMenu().getDBLoc();

	private static final String NAME_CNT = "select count(*) from in_room_menu where org_id = :orgId and "
			+ " property_id = :propId and category_id = :catId and subcategory_id = :subId and item_id = :itemId and auto_item_id = :autoId" +
			" and id <> :id and active = true ";
	
	private static final String FIND = "from InRoomMenu where orgId = :orgId and "
			+ " propertyId = :propId";

	@Autowired
	private ConnectionManager connMgr;

	@Override
	protected Class<InRoomMenu> getCls() {
		return InRoomMenu.class;
	}

	@Override
	protected ConnectionManager getConnectionManager() {
		return connMgr;
	}

	@Override
	protected DBLoc getDBLoc() {
		return DBLoc;
	}

	@Override
	public <E extends InRoomMenu> E get(Class<E> cls, long id) {
		return (E) getConnectionManager().getCurrentSession(getDBLoc()).load(cls, id);
	}

	@Override
	public <E extends InRoomMenu> void save(E loc) {
		getConnectionManager().getCurrentSession(DBLoc).saveOrUpdate(loc);
	}

	@Override
	public boolean isInRoomMenuTaken(long orgId, long propId, Long id, long categoryId, Long subcategoryId,
			Long itemId, Long autoSuggestionItemId, long versionId) {
		Query q = connMgr.getCurrentSession(getDBLoc()).createSQLQuery(NAME_CNT);
		q.setLong("id", id == null ? -1 : id);
		q.setLong("orgId", orgId);
		q.setParameter("propId", propId, Hibernate.LONG);
		q.setLong("catId", categoryId);
		q.setLong("subId", subcategoryId);
		q.setLong("itemId", itemId);
		q.setLong("autoId", autoSuggestionItemId);
		return ((Number) q.uniqueResult()).intValue() > 0;
	}

	@Override
	public List<InRoomMenu> getInRoomMenuList(long orgId, long propId, long versionId) {
		Query q = connMgr.getCurrentSession(getDBLoc()).createQuery(FIND);
		q.setLong("orgId", orgId);
		q.setParameter("propId", propId, Hibernate.LONG);
		return q.list();
	}

	@Override
	public void permDeleteAll(long orgId, long propId) {
		SQLQuery q = connMgr.getCurrentSession(getDBLoc()).createSQLQuery(DEL_ALL);
		q.setLong("orgId", orgId);
		q.setLong("propertyId", propId);
		q.executeUpdate();
	}
	
	

}
